﻿using Dapper_Core.Model;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace Dapper_Core.Common
{
    public static class SessionMemoryUtility
    {
        /// <summary>
        /// 获取用户基本信息
        /// </summary>
        /// <returns></returns>
        public static BasicUserInfo GetBasicUserInfo()
        {
            return GetSessionData<BasicUserInfo>("BasicUserInfo");
        }

        /// <summary>
        /// 设置用户基本信息
        /// </summary>
        /// <param name="userInfo"></param>
        public static void SetBasicUserInfo(BasicUserInfo userInfo)
        {
            SetSessionData("BasicUserInfo", userInfo);
        }

        /// <summary>
        /// 获取Session的值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">Session的键</param>
        /// <returns></returns>
        public static T GetSessionData<T>(string key)
        {
            if (MyHttpContext.Current.Session.Get(key) == null)
            {
                return default(T);
            }
            string temporary = Encoding.Default.GetString(MyHttpContext.Current.Session.Get(key));
            return JsonConvert.DeserializeObject<T>(temporary);
        }

        /// <summary>
        /// 设置Session的值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">Session的键</param>
        /// <returns></returns>
        public static void SetSessionData<T>(string key, T value)
        {
            byte[] bytes = Encoding.Default.GetBytes(JsonConvert.SerializeObject(value));
            MyHttpContext.Current.Session.Set(key, bytes);
        }

        /// <summary>
        /// 清空Session
        /// </summary>
        public static void ClearSession()
        {
            MyHttpContext.Current.Session.Clear();
        }
    }
}
